﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.IO;
using System.Xml;
using System.Windows.Forms;
using Common;

namespace WoodManager.UI
{
    public partial class ChiTietModule : Form
    {
        ConnectManager cm = new ConnectManager();
        Validator vali = new Validator();
        DataTable tbNhomModule, tbModuleDetails, tbListVan;
        DataTable tbLoiVan, tbPhuMat1, tbPhuMat2, tbChiCanh, tbSoCanhSon;
        double LenCanh;
        double dDai, dRong;
        int isLoad = 0;
        string sModuleID = "", sChiTietIdOld = "";
        string sNhomModule = "", sNhomModule2 = "";

        public ChiTietModule()
        {
            InitializeComponent();
            loadData();
            loadTreeView();
            loadNhomVan();
            isLoad = 1;
        }

        private void loadNhomVan()
        {

            DataTable tbNhomVan = cm.getTable("Select distinct NhomVan from ModuleDetails");
            cbbNhomVan.DataSource = tbNhomVan;
            cbbNhomVan.DisplayMember = "NhomVan";
            cbbNhomVan.ValueMember = "NhomVan";

            //Lay du lieu tu file XML
            //DataSet dsCbb = new DataSet();
            //DataTable tbNhomVan = new DataTable("NhomVan");

            //XmlTextReader xmlRead = new XmlTextReader("DataCombobox.xml");

            //dsCbb.ReadXml(xmlRead);

            //xmlRead.Close();

            //MessageBox.Show(dsCbb.Tables[0].Rows.Count.ToString());

            //cbbNhomVan.DataSource = dsCbb.Tables[0];
            //cbbNhomVan.DisplayMember = "lable";
            //cbbNhomVan.ValueMember = "data";
        }

        private void loadTreeView()
        {
            treeModule.Nodes.Clear();

            if (cm.conn.State == ConnectionState.Closed)
                cm.conn.Open();
            tbNhomModule = cm.getTable("Select * from NhomModule");
            TreeNode level1;
            for (int i = 0; i < tbNhomModule.Rows.Count; i++)
            {
                DataTable tbNhomModule2 = cm.getTable("select * from NhomModule2 where NhomModuleID = N'"+tbNhomModule.Rows[i]["NhomModuleID"].ToString()+"'");
                if (tbNhomModule2.Rows.Count > 0)
                {
                    TreeNode[] level2 = new TreeNode[tbNhomModule2.Rows.Count];
                    for (int i2 = 0; i2 < tbNhomModule2.Rows.Count; i2++)
                    { 
                        DataTable tbModule = cm.getTable("Select ModuleID, TenModule, NhomModule2ID from Module where NhomModule2ID = N'" + tbNhomModule2.Rows[i2]["NhomModule2ID"].ToString() + "'");
                        if (tbModule.Rows.Count > 0)
                        {
                            TreeNode[] level3 = new TreeNode[tbModule.Rows.Count];
                            for (int i3 = 0; i3 < tbModule.Rows.Count; i3++)
                            {
                                level3[i3] = new TreeNode(tbModule.Rows[i3]["TenModule"].ToString());
                                level3[i3].Name = tbModule.Rows[i3]["ModuleID"].ToString();
                            }
                            level2[i2] = new TreeNode(tbNhomModule2.Rows[i2]["TenNhomModule2"].ToString(), level3);
                        }
                        else
                        {
                            level2[i2] = new TreeNode(tbNhomModule2.Rows[i2]["TenNhomModule2"].ToString());
                        }
                        level2[i2].Name = tbNhomModule2.Rows[i2]["NhomModule2ID"].ToString();                      
                    }
                    level1 = new TreeNode(tbNhomModule.Rows[i]["TenNhomModule"].ToString(),level2);
                }
                else
                {
                    level1 = new TreeNode(tbNhomModule.Rows[i]["TenNhomModule"].ToString());
                }
                level1.Name = tbNhomModule.Rows[i]["NhomModuleID"].ToString();

                treeModule.Nodes.Add(level1);
                
            }
            if (cm.conn.State == ConnectionState.Open)
                cm.conn.Close();
        }

        private void loadData()
        {
            tbListVan = cm.getTable("select * from ListVan");
            cbbTenChiTiet.DataSource = tbListVan;
            cbbTenChiTiet.DisplayMember = "TenVan";
            cbbTenChiTiet.ValueMember = "VanID";

            tbLoiVan = cm.getTable("select IDVan, NhomVan, TenVan from ViewVanVatLieu order by NhomVan");
            cbbMaLoiVan.DataSource = tbLoiVan;
            cbbMaLoiVan.DisplayMember = "TenVan";
            cbbMaLoiVan.ValueMember = "IDVan";

            tbPhuMat1 = cm.getTable("select IDSon, NhomSon, ChiTiet from SonPhu order by NhomSon");
            tbPhuMat2 = cm.getTable("select IDSon, NhomSon, ChiTiet from SonPhu order by NhomSon");
            cbbPhuMat1.DataSource = tbPhuMat1;
            cbbPhuMat1.DisplayMember = "ChiTiet";
            cbbPhuMat1.ValueMember = "IDSon";
            cbbPhuMat2.DataSource = tbPhuMat2;
            cbbPhuMat2.DisplayMember = "ChiTiet";
            cbbPhuMat2.ValueMember = "IDSon";

            //tbChiCanh = cm.getTable("Select IDChiCanh, TenChiCanh from ChiCanh");
            //cbbChiCanh.DataSource = tbChiCanh;
            //cbbChiCanh.DisplayMember = "TenChiCanh";
            //cbbChiCanh.ValueMember = "IDChiCanh";

            //tbSoCanhSon = cm.getTable("Select * from SonChiCanh");
            //cbbSoCanhSon.DataSource = tbSoCanhSon;
            //cbbSoCanhSon.DisplayMember = "ChiTiet";
            //cbbSoCanhSon.ValueMember = "ID";
        }

        private void loadDataGrid(string moduleID)
        {
            tbModuleDetails = cm.getTable("select * from ViewModuleDetails where [Mã Module] = N'"+moduleID+"'");
            dtgModuleDetail.DataSource = tbModuleDetails;
        }

        private void CalSquare()
        {
            switch (cbbSoCanhSon.SelectedValue.ToString())
            {
                case "0":
                    LenCanh = 0.0;
                    break;
                case "1":
                    LenCanh = dDai * double.Parse(txtSoLuong.Text) / 1000;
                    break;
                case "2":
                    LenCanh = dRong * double.Parse(txtSoLuong.Text) / 1000;
                    break;
                case "3":
                    LenCanh = (dDai + dRong) * double.Parse(txtSoLuong.Text) / 1000;
                    break;
                case "4":
                    LenCanh = (dDai + 2 * dRong) * double.Parse(txtSoLuong.Text) / 1000;
                    break;
                case "5":
                    LenCanh = (2 * dDai + dRong) * double.Parse(txtSoLuong.Text) / 1000;
                    break;
                case "6":
                    LenCanh = 2 * dRong * double.Parse(txtSoLuong.Text) / 1000;
                    break;
                case "7":
                    LenCanh = 2 * dDai * double.Parse(txtSoLuong.Text) / 1000;
                    break;
                case "8":
                    LenCanh = (dDai + dRong) * 2 * double.Parse(txtSoLuong.Text) / 1000;
                    break;
            }

        }

        private void cbbTenChiTiet_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isLoad != 0)
            {
                dDai = double.Parse(tbListVan.Rows[cbbTenChiTiet.SelectedIndex]["Dai"].ToString());
                dRong = double.Parse(tbListVan.Rows[cbbTenChiTiet.SelectedIndex]["Rong"].ToString());
            }
        }

        private void treeModule_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Node.IsExpanded)
                return;
                

            if (e.Node.Level == 0)
            {
                treeModule.CollapseAll();
                e.Node.Expand();
                sNhomModule = e.Node.Name;
            }
            else if (e.Node.Level == 1)
            {
                treeModule.CollapseAll();
                e.Node.Expand();
                sNhomModule2 = e.Node.Name;
            }

            if (e.Node.Level == 2)
            {
                sModuleID = e.Node.Name.ToString();
                loadDataGrid(sModuleID);

                if (e.Button == MouseButtons.Right)
                    this.ctxTreeModule.Show(Cursor.Position);
            }
            else
                sModuleID = "";

            
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (sModuleID == "")
                return;
            try
            {
                if (cm.conn.State == ConnectionState.Closed)
                    cm.conn.Open();
                string sInsert0 = "InsertModuleDetails N'" + sModuleID + "', N'" + cbbTenChiTiet.SelectedValue.ToString() + "',";
                string sInsert1 = "N'" + cbbMaLoiVan.SelectedValue.ToString() + "', N'"+cbbNhomVan.Text+"' , N'" + double.Parse(txtSoLuong.Text) + "',";
                string sInsert2 = "N'" + cbbPhuMat1.SelectedValue.ToString() + "',N'" + cbbPhuMat2.SelectedValue.ToString() + "',";
                string sInsert3 = "N'" + cbbChiCanh.SelectedValue.ToString() + "',N'" + cbbSoCanhSon.SelectedValue.ToString() + "'";
                string sInsert = sInsert0 + sInsert1 + sInsert2 + sInsert3;

                SqlCommand sqlInsert = new SqlCommand(sInsert, cm.conn);

                sqlInsert.ExecuteNonQuery();
                loadDataGrid(sModuleID);

                if (cm.conn.State == ConnectionState.Open)
                    cm.conn.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public delegate void getModule(DataTable tbModule1);
        public getModule getData;

        private void btnInsert_Click(object sender, EventArgs e)
        {
            if (!vali.checkNumber(txtSoLuong.Text))
            {
                MessageBox.Show("Số lượng phải là số");
                return;
            }
            if (getData != null)
            {
                for (int i = 0; i < tbModuleDetails.Rows.Count; i++)
                {
                    tbModuleDetails.Rows[i]["số lượng"] = int.Parse(tbModuleDetails.Rows[i]["số lượng"].ToString()) * int.Parse(txtSLCopy.Text);
                }
                getData(tbModuleDetails);
                this.Close();
            }
        }

        private void btnChange_Click(object sender, EventArgs e)
        {
            try
            {
                if (cm.conn.State == ConnectionState.Closed)
                    cm.conn.Open();
                string sUpdate0 = "UpdateModuleDetails N'" + sModuleID + "', N'" + cbbTenChiTiet.SelectedValue.ToString() + "',";
                string sUpdate1 = "N'" + cbbMaLoiVan.SelectedValue.ToString() + "', N'" + cbbNhomVan.Text + "' ,N'" + double.Parse(txtSoLuong.Text) + "',";
                string sUpdate2 = "N'" + cbbPhuMat1.SelectedValue.ToString() + "',N'" + cbbPhuMat2.SelectedValue.ToString() + "',";
                string sUpdate3 = "N'" + cbbChiCanh.SelectedValue.ToString() + "',N'" + cbbSoCanhSon.SelectedValue.ToString() + "',N'" + sChiTietIdOld + "'";
                string sUpdate = sUpdate0 + sUpdate1 + sUpdate2 + sUpdate3;

                SqlCommand sqlUpdate = new SqlCommand(sUpdate, cm.conn);

                sqlUpdate.ExecuteNonQuery();
                loadDataGrid(sModuleID);

                if (cm.conn.State == ConnectionState.Open)
                    cm.conn.Close();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dtgModuleDetail_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1)
                return;

            cbbTenChiTiet.SelectedValue =  this.tbModuleDetails.Rows[e.RowIndex]["Mã Chi Tiết"];
            cbbMaLoiVan.Text = this.tbModuleDetails.Rows[e.RowIndex]["Ván lõi"].ToString();
            txtSoLuong.Text = this.tbModuleDetails.Rows[e.RowIndex]["số lượng"].ToString();
            cbbNhomVan.Text = this.tbModuleDetails.Rows[e.RowIndex]["Nhóm Ván"].ToString();
            cbbPhuMat1.SelectedValue = this.tbModuleDetails.Rows[e.RowIndex]["Phủ 1"];
            cbbPhuMat2.SelectedValue = this.tbModuleDetails.Rows[e.RowIndex]["Phủ 2"];
            cbbChiCanh.SelectedValue = this.tbModuleDetails.Rows[e.RowIndex]["Mã Chỉ Cạnh"];
            cbbSoCanhSon.SelectedValue = this.tbModuleDetails.Rows[e.RowIndex]["Số Cạnh Sơn"];

            sChiTietIdOld = this.tbModuleDetails.Rows[e.RowIndex]["Mã Chi Tiết"].ToString();

        
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            this.Refresh();
        }

        private void ctxTreeModule_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem.Name == "makeCopy")
            {
                CopyModule frmCopy = new CopyModule();

                frmCopy.loadTree = new CopyModule.loadTreeView(loadTreeView);

                frmCopy.ShowDialog();
            }
        }

        private void deleteModuleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("bạn có chắc muốn xóa Module này không?", "Xác nhận xóa", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    if (cm.conn.State == ConnectionState.Closed)
                        cm.conn.Open();

                    SqlCommand sqlDelModuleDetails = new SqlCommand("Delete ModuleDetails where ModuleID = N'" + sModuleID + "'", cm.conn);
                    SqlCommand sqlDelModule = new SqlCommand("Delete Module where ModuleID = N'" + sModuleID + "'", cm.conn);
                    sqlDelModuleDetails.ExecuteNonQuery();
                    sqlDelModule.ExecuteNonQuery();

                    MessageBox.Show("Đã xóa module thành công");
                    loadTreeView();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        }

        


    }
